package com.other.api;

import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XingyouTool {
    private static final Logger logger = LoggerFactory.getLogger(XingyouTool.class);

    /**
     * 构建星游Sign签名
     * @param params
     * @param xingyouKey
     * @return
     */
    public static String getSign(JsonObject params,String xingyouKey){
        Map<String, String> paramsMap = new HashMap<String, String>();
        Iterator<Map.Entry<String, Object>> it = params.iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String key = entry.getKey();
            String value = String.valueOf(entry.getValue());
            if (value == null) {
                value = "";
            }
            paramsMap.put(key, value);
        }
        return getSign(paramsMap,xingyouKey);
    }

    public static String getSign(Map<String, String> paramsMap,String xingyouKey){
        //构建Sign签名
        String postData = Tool.getSignCheckContent(paramsMap, false);
        String sign = Tool.md5encrypt32(postData + "&" + xingyouKey).toLowerCase();
        logger.info("xingyou getsign : " + postData + "&" + xingyouKey + " sign:" + sign);
        return sign;
    }

    /**
     * 星游API 推送微信订阅消息
     * @return
     */
    public static Future<JsonObject> sendWxSubscribe(WebClient webClient, int cchid, int appid,String xingyouKey, String openId, String wxMsgid, JsonObject wxData, long userId) {
        Promise<JsonObject> promise = Promise.promise();
        try{
            //发起微信订阅消息推送
            JsonObject params = new JsonObject();
            params.put("cchid", cchid);
            params.put("appid", appid);
            params.put("openid", openId);//推送人openId
            params.put("template_id", wxMsgid);//模版id
//            params.put("page", "index");
            params.put("data", wxData);

            //构建Sign签名
            String sign = getSign(params,xingyouKey);

            params.put("sign", sign);
            String url = "https://channel.ixyn.cn/v1/game/send_subscribe_message";
            String postData = "appid="+appid+"&cchid="+cchid+"&openid="+ openId+"&template_id="+ wxMsgid+"&data="+ wxData +"&sign="+sign;
            Buffer buffer = Buffer.buffer(postData, "UTF-8");
            webClient.postAbs(url).putHeader("content-type", "application/x-www-form-urlencoded").timeout(5000).sendBuffer(buffer, h -> {
                if (h.succeeded()) {
                    HttpResponse<Buffer> response = h.result();
                    JsonObject resObj = response.bodyAsJsonObject();
                    promise.complete(resObj);
                    logger.info("### Xingyou API sendWxSubscribe  resObj:" + resObj  + " taskinfo => userid:" + userId + " postData : " + postData);
                }
            });


        }catch (Exception e){
            logger.error("#### Xingyou API sendWxSubscribe Exception cause = " + Tool.getException(e));
            promise.fail("Xingyou API sendWxSubscribe errro : " +Tool.getException(e));
        }
        return promise.future();
    }

    /**
     * 星游API 微信文本合规检查
     * @return
     */
    public static Future<Boolean> wxMsgSecCheck(WebClient webClient, int cchid, int appid,String xingyouKey, String openId, String content) {
        Promise<Boolean> promise = Promise.promise();
        try{
            long curTime = TimeUtils.getCurTime();
            //发起微信订阅消息推送
            JsonObject params = new JsonObject();
            params.put("tm", curTime);
            params.put("cchid", cchid);
            params.put("appid", appid);
            params.put("openid", openId);//推送人openId
            params.put("scene", 1);//场景值(1:资料， 2:评论， 3:论坛， 4:社交日志)
            params.put("content", content);

            //构建Sign签名
            String sign = getSign(params,xingyouKey);

            params.put("sign", sign);
            String url = "https://channel.ixyn.cn/v1/game/msg_sec_check";
            String postData = "appid="+appid+"&cchid="+cchid+"&tm="+curTime+"&openid="+ openId+"&scene="+ 1+"&content="+ URLEncoder.encode(content)+"&sign="+sign;
            Buffer buffer = Buffer.buffer(postData, "UTF-8");
            webClient.postAbs(url).putHeader("content-type", "application/x-www-form-urlencoded").timeout(5000).sendBuffer(buffer, h -> {
                if (h.succeeded()) {
                    HttpResponse<Buffer> response = h.result();
                    JsonObject resObj = response.bodyAsJsonObject();
                    int code = resObj.getInteger("code");//200-成功，其他失败
                    if (code == 200) {
                        JsonObject data = resObj.getJsonObject("data");
                        boolean pass = data.getBoolean("pass");
                        logger.info("Xingyou API msgSecCheck success content:{} result:{} postData:{}",content, resObj,postData);
                        promise.complete(pass);
                    } else {
                        // 星游api请求失败
                        logger.error("Xingyou API msgSecCheck label error content:{} result:{} postData:{}",content, resObj,postData);
                        promise.complete(false);
                    }
                    logger.info("### Xingyou API msgSecCheck  resObj:" + resObj);
                }
            });


        }catch (Exception e){
            logger.error("#### Xingyou API msgSecCheck Exception cause = " + Tool.getException(e));
            promise.fail("Xingyou API msgSecCheck errro : " +Tool.getException(e));
        }
        return promise.future();
    }
}
